package com.rookie.im.learn.io.netty.protocol.test;


import io.netty.util.CharsetUtil;
import org.junit.Test;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class SimpleClient {
    private final String msg = "你好呀 Netty\n";
    private final Charset charset = CharsetUtil.UTF_8;

    @Test
    public void testSimpleMsg() {
        try (Socket socket = creatSocket()) {
            OutputStream outputStream = socket.getOutputStream();
            for (int i = 0; i < 10; ++i) {
                outputStream.write(msg.getBytes(charset));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @Test
    public void testDecodeMsg() {
        try (Socket socket = creatSocket()) {
            OutputStream outputStream = socket.getOutputStream();
            byte[] data = msg.getBytes(charset);
            int length = data.length;
            byte[] data_head = ByteBuffer.allocate(4).putInt(length).array();
            for (int i = 0; i < 10; ++i) {
                outputStream.write(data_head);
                outputStream.write(data);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private Socket creatSocket() throws IOException {
        String host = "localhost";
        int port = 9000;
        return new Socket(host, port);
    }
}
